package com.dmall.chapter04.section02;

import com.dmall.chapter02.section09.Graph;

import java.util.ArrayList;

/**
 * 求一个图的联通分量
 * 使用int类型数组
 * @author wx
 * @date 2020-02-24 21:29:55
 */
public class CC {

    private Graph G;
    private int[] visited;
    private int cccount = 0;

    public CC(Graph G) {
        this.G = G;
        this.visited = new int[G.V()];
        for (int i = 0; i < visited.length; i ++) {
            this.visited[i] = -1;
        }
        for (int v = 0; v < G.V(); v++) {
            if (visited[v] == -1) {
                dfs(v, cccount);
                cccount ++;
            }
        }
    }

    private void dfs(int v, int ccid) {
        visited[v] = ccid;
        for (int w : G.adj(v)) {
            if (visited[w] == -1) {
                dfs(w, ccid);
            }
        }
    }

    public int count() {
//        for (int e : visited) {
//            System.out.print(e + " ");
//        }
//        System.out.println();
        return cccount;
    }

    public boolean isConnected(int v, int w) {
        G.validateVertex(v);
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    public ArrayList<Integer>[] components() {
        ArrayList<Integer>[] res = new ArrayList[cccount];
        for (int i = 0; i < cccount; i++) {
            res[i] = new ArrayList<>();
        }
        for (int i = 0; i < visited.length; i++) {
            res[visited[i]].add(i);
        }
        return res;
    }

    public static void main(String[] args) {
        String filename = CC.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CC cc = new CC(g);
        System.out.println(cc.count());

        System.out.println(cc.isConnected(0, 6));
        System.out.println(cc.isConnected(0, 5));

        ArrayList<Integer>[] comps = cc.components();
        for (int ccid = 0; ccid < comps.length; ccid++) {
            ArrayList<Integer> comp = comps[ccid];
            System.out.print(ccid + " : ");
            for (Integer v : comp) {
                System.out.print(v + " ");
            }
            System.out.println();
        }
    }
}